<html>
    <head>
        {php}html_header_show();{/php}
        <link rel="stylesheet" href="{$WEBROOT}/patients/css/nightingale.css" type="text/css"/>
        <link rel="stylesheet" href="{$WEBROOT}/interface/themes/jquery.autocomplete.css" type="text/css">
        {literal}
        <style type="text/css">
            .text {
                font-size: 9pt;
            }
        </style>
        {/literal}


        <!--<script type="text/javascript" src="{$WEBROOT}/library/dialog.js"></script>-->
        <script type="text/javascript" src="{$WEBROOT}/library/js/jquery-1.2.2.min.js"></script>
        <script type="text/javascript" src="{$WEBROOT}/library/js/jquery.bgiframe.min.js"></script>
        <script type="text/javascript" src="{$WEBROOT}/library/js/jquery.dimensions.pack.js"></script>
        <script type="text/javascript" src="{$WEBROOT}/library/js/jquery.autocomplete.pack.js"></script>

        {literal}
        <script language='JavaScript'>

            // This holds all the default drug attributes.
            {/literal}
                    var drugopts = [{$DRUG_ATTRIBUTES}];
            {
            literal
            }

            // Helper to choose an option from its value.
            function selchoose(sel, value) {
            var o = sel.options;
                    for (i = 0; i < o.length; ++i) {
            o[i].selected = (o[i].value == value);
            }
            }

            // Fill in default values when a drop-down drug is selected.
            function drugselected(sel) {
            var f = document.forms[0];
                    var i = f.drug_id.selectedIndex - 1;
                    if (i >= 0) {
            var d = drugopts[i];
                    f.drug.value = d[0];
                    selchoose(f.form, d[1]);
                    f.dosage.value = d[2];
                    f.size.value = d[3];
                    selchoose(f.unit, d[4]);
                    selchoose(f.route, d[5]);
                    selchoose(f.interval, d[6]);
                    selchoose(f.substitute, d[7]);
                    f.quantity.value = d[8];
                    f.disp_quantity.value = d[8];
                    selchoose(f.refills, d[9]);
                    f.per_refill.value = d[10];
            }
            }

            // Invoke the popup to dispense a drug.
            function dispense() {
            var f = document.forms[0];
                    dlgopen('interface/drugs/dispense_drug.php' +
            {/literal}'?drug_id={$prescription->get_drug_id()}' +{literal}
                    '&prescription=' + f.id.value +
                    '&quantity=' + f.disp_quantity.value +
                    '&fee=' + f.disp_fee.value,
                    '_blank', 400, 200
                    );
            }

            function quantityChanged() {
            var f = document.forms[0];
                    f.per_refill.value = f.quantity.value;
                    if (f.disp_quantity) {
            f.disp_quantity.value = f.quantity.value;
            }
            }

        </script>
        {/literal}
    </head>
    <body class="body_top">

        <form name="prescribe" id="prescribe" method="post" action="{$FORM_ACTION}">
            <div class="borde_normal">
                <span class="historial_paciente"><i style="font-size: 1.4em;" class="icon-list-alt"></i> {xl t='Prescription'} </span>

                <a href="#" onclick="submitfun();" id="ok" class="css_button"><span><i class="icon-ok-sign" style="font-size: 25px;"></i> {xl t='Save'}</span></a>

                <a href="" id="cancel" class="css_button"><span><i class="icon-remove-sign" style="font-size: 25px;"></i> {xl t='Cancel'}</span></a>
            </div>

            {php} if ($GLOBALS['enable_amc_prompting']) { {/php}
            <div style='float:right;'>
                <div>
                    {if $DRUG_ARRAY_VALUES}
                    {if $prescription->get_refills() >= $prescription->get_dispensation_count()}
                    <!--<input type="submit" name="disp_button" value="{xl t='Save and Dispense'}" />-->
                    <input type="text" name="disp_quantity" size="2" maxlength="10" value="{$DISP_QUANTITY}" />
                    {xl t='units'}, $
                    <input type="text" name="disp_fee" size="5" maxlength="10" value="{$DISP_FEE}" />
                    {else}&nbsp;
                    {xl t='prescription has reached its limit of'} {$prescription->get_refills()} {xl t='refills'}.
                    {/if}
                    {/if}
                </div>
                <div style='float:left;margin:5px 5px 5px 5px;'>
                    {amcCollect amc_id='e_prescribe_amc' patient_id=$prescription->patient->id object_category='prescriptions' object_id=$prescription->id}
                    {if not $amcCollectReturn}
                    <input type="checkbox" id="escribe_flag" name="escribe_flag">
                    {else}
                    <input type="checkbox" id="escribe_flag" name="escribe_flag" checked>
                    {/if}
                    <span class="text">{xl t='E-Prescription?'}</span><br>
                </div>
            </div>
            {php} } {/php}

            <table CELLSPACING="0" CELLPADDING="3" BORDER="0">
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Currently Active'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        <input type="checkbox" name="active" value="1"{if $prescription->get_active() > 0} checked{/if} />
                    </td>
                </tr>
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Starting Date'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        {html_select_date start_year="-10" end_year="+5" time=$prescription->start_date prefix="start_date_"}
                    </td>
                </tr>
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Provider'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        {html_options name="provider_id" options=$prescription->provider->utility_provider_array() selected=$prescription->provider->get_id()}
                        <input type="hidden" name="patient_id" value="{$prescription->patient->id}" />
                    </td>
                </tr>
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Drug'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        <textarea rows="2" cols="30" name="drug" name="drug" id="drug"></textarea>
                        <input type="hidden" name="drug_id" id="drug_id" value="0" />
                        <!--<input type="input" size="20" name="drug" id="drug" value="{$prescription->drug}"/>-->
                        <!--<a href="javascript:;" id="druglookup" class="small" name="B4" onclick="$('#hiddendiv').show();
                        document.getElementById('hiddendiv').innerHTML = '&lt;iframe src=&quot;controller.php?prescription&amp;lookup&amp;drug=&quot; width=&quot;100%&quot;height=&quot;52&quot; scrolling=&quot;no&quot; frameborder=&quot;no&quot;&gt;&lt;/iframe&gt;'">
                            ({xl t='click here to search'})</a>-->
                        <div id=hiddendiv style="display:none">&nbsp;</div>
                    </td>
                </tr>
                {if $DRUG_ARRAY_VALUES}
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >&nbsp; {xl t='in-house'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        <!--select name="drug_id" onchange="drugselected(this)">
                            {html_options values=$DRUG_ARRAY_VALUES output=$DRUG_ARRAY_OUTPUT selected=$prescription->get_drug_id()}
                        </select-->
                    </td>
                </tr>
                {/if}
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Quantity'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        <input TYPE="TEXT" NAME="quantity" id="quantity" SIZE="10" MAXLENGTH="31"
                               VALUE="{$prescription->quantity}"
                               onchange="quantityChanged()" />
                    </td>
                </tr>
                {if $SIMPLIFIED_PRESCRIPTIONS && !$prescription->size}
                <tr style='display:none;'>
                    {else}
                <tr>
                    {/if}
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Medicine Units'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        <select  NAME="size" id="size" ></select>
                        <!--input TYPE="TEXT" NAME="size" id="size" SIZE="11" MAXLENGTH="10" VALUE="{$prescription->size}"/-->
                        <select name="unit" id="unit"></select>
                        <!--select name="unit" id="unit">{html_options options=$prescription->unit_array selected=$prescription->unit}</select-->
                    </td>
                </tr>
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Take'}</td>
                    <td COLSPAN="2" class="text" ALIGN="LEFT" VALIGN="MIDDLE" >
                        {if $SIMPLIFIED_PRESCRIPTIONS && !$prescription->form && !$prescription->route && !$prescription->interval}
                        <input TYPE="text" NAME="dosage" id="dosage" SIZE="30" MAXLENGTH="100" VALUE="{$prescription->dosage}" />
                        <input type="hidden" name="form" id="form" value="0" />
                        <input type="hidden" name="route" id="route" value="0" />
                        
                        <input type="hidden" name="interval" id="interval" value="0" />
                        {else}
                        <input TYPE="TEXT" NAME="dosage" id="dosage" SIZE="2" MAXLENGTH="10" VALUE="{$prescription->dosage}"/> {xl t='in'}
                        <!--select name="form" id="form">{html_options options=$prescription->form_array selected=$prescription->form}</select-->
                        <select name="form" id="form"></select>
                        <!--select name="route" id="route">{html_options options=$prescription->route_array selected=$prescription->route}</select-->
                        <select name="route" id="route"></select>
                        <select name="interval" id="interval">{html_options options=$prescription->interval_array selected=$prescription->interval}</select>

                        {/if}
                    </td>
                </tr>
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Refills'}</td>
                    <td COLSPAN="2" class="text" ALIGN="LEFT" VALIGN="MIDDLE" >
                        {html_options name="refills" options=$prescription->refills_array selected=$prescription->refills}
                        {if $SIMPLIFIED_PRESCRIPTIONS}
                        <input TYPE="hidden" ID="per_refill" NAME="per_refill" VALUE="{$prescription->per_refill}" />
                        {else}
                        &nbsp; &nbsp; # {xl t='of tablets'}:
                        <input TYPE="TEXT" ID="per_refill" NAME="per_refill" SIZE="2" MAXLENGTH="10" VALUE="{$prescription->per_refill}" />
                        {/if}
                    </td>
                </tr>
                <tr>
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Notes'}</td>
                    <td COLSPAN="2" class="text" ALIGN="LEFT" VALIGN="MIDDLE" >
                        <textarea name="note" id="note" cols="30" rows="2" wrap="virtual">{$prescription->note}</textarea>
                    </td>
                </tr>
                <tr>
                    {if $WEIGHT_LOSS_CLINIC}
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Substitution'}</td>
                    <td COLSPAN="2" ALIGN="LEFT" VALIGN="MIDDLE" >
                        {html_options name="substitute" options=$prescription->substitute_array selected=$prescription->substitute}
                    </td>
                    {else}
                    <td COLSPAN="1" class="text" ALIGN="right" VALIGN="MIDDLE" >{xl t='Add to Medication List'}</td>
                    <td COLSPAN="2" class="text" ALIGN="LEFT" VALIGN="MIDDLE" >
                        {html_radios name="medication" options=$prescription->medication_array selected=$prescription->medication}
                        &nbsp; &nbsp;
                        {html_options name="substitute" options=$prescription->substitute_array selected=$prescription->substitute}
                    </td>
                    {/if}
                </tr>
            </table>

            <input type="hidden" name="id" value="{$prescription->id}" />
            <input type="hidden" name="process" value="{$PROCESS}" />
            <script language='JavaScript'>
            {
            $ENDING_JAVASCRIPT
            }
            </script>
        </form>
        {literal}
        <!-- for the fancy jQuery stuff -->
        <script type="text/javascript">

            function submitfun() {
                top.restoreSession();
                        if (CheckForErrors(this)) {
                            //alert( $("#prescribe").attr('action')) ;
                //document.forms["prescribe"].submit();
                $.post( $("#prescribe").attr('action'), $( "#prescribe" ).serialize()  );
                $("#drug").val("");
                $("#quantity").val("");
                $('#size').children().remove();
                $('#form').children().remove();
                $('#route').children().remove();
                $('#unit').children().remove();
                $('#dosage').val("");
                $('#per_refill').val("");
                $('#note').val("");
                $('#interval').val(0);
                $('#refills').val(1);
                alert( "La prescripción se guardo correctamente." );
                
                }
                else {
                return false;
                }
            }

            function add_unidad(element, index, array){
            //	alert(element);
            $('#unit').append($('<option value = ' + element + '>' + element + '</option>'));
            }

            function add_cantidad(element, index, array){
            //alert(element);
            $('#size').append($('<option value = ' + element + '>' + element + '</option>'));
            }

            function add_adm(element, index, array){
            //alert(element);
            $('#route').append($('<option value = ' + element + '>' + element + '</option>'));
            }

            function add_uniref(element, index, array){
            //alert(element);
            $('#form').append($('<option value = ' + element + '>' + element + '</option>'));
            }

            function iframetopardiv(string) {
            var name = string
                    document.getElementById('drug').value = name;
                    $("#hiddendiv").html("&nbsp;");
                    $('#hiddendiv').hide();
            }

            function cancelParlookup() {
            $('#hiddendiv').hide();
                    $("#hiddendiv").html("&nbsp;");
            }

            $().ready(function() {
				$("#cancel").click(function() {
					parent.jQuery.fancybox.close();
				});
				
				$("#drug").autocomplete('library/ajax/prescription_drugname_lookup.php',
				{
				width: 300,
						scrollHeight: 200,
						selectFirst: true
				});
						$("#drug").result(function(event, data, formatted) {
				//$("#form_patient").val(data[0]);
				//$("#form_pid").val(data[1]);
                                        $("#drug_id").val(data[1]);
				$('#unit').empty();
						$('#size').empty();
						$('#route').empty();
						$('#form').empty();
						$.getJSON('library/ajax/prescription_drug_info.php?drug_id=' + data[1], function(data) {
				var unidad_s = [];
						var cantidad_s = [];
						var adm_s = [];
						var unidad_ref_s = [];
						$.each(data, function(key, val) {

				var unidad = val.unidad;
						var cantidad = val.cantidad;
						var adm = val.administracion;
						var unidad_ref = val.unidad_referencia;
						var result = - 2;
						result = unidad_s.indexOf(unidad, 0);
						if (result == - 1){
				unidad_s.push(unidad);
				}

				var result = - 2;
						result = cantidad_s.indexOf(cantidad, 0);
						if (result == - 1){
				cantidad_s.push(cantidad);
				}

				var result = - 2;
						result = adm_s.indexOf(adm, 0);
						if (result == - 1){
				adm_s.push(adm);
				}

				var result = - 2;
						result = unidad_ref_s.indexOf(unidad_ref, 0);
						if (result == - 1){
				unidad_ref_s.push(unidad_ref);
				}
			   });
						unidad_s.forEach(add_unidad);
						cantidad_s.forEach(add_cantidad);
						adm_s.forEach(add_adm);
						unidad_ref_s.forEach(add_uniref);
				});
				});
						$("#drug").focus();
						$("#prescribe").submit(function() {
				return CheckForErrors(this)
				});
						$("#druglookup").click(function() {
				DoDrugLookup(this)
				});
            });
                    // pop up a drug lookup window with the value of the drug name, if we have one
                            function DoDrugLookup(eObj) {
                            drugname = "";
                                    if ($('#drug').val() != "") {
                            drugname = $('#drug').val();
                            }
                            $("#druglist").css('display', 'block');
                                    document.lookup.action = 'controller.php?prescription&edit&id=&pid={/literal}{$prescription->patient->id}{literal}&drug=sss' + drugname;
                                    drugPopup = window.open('controller.php?prescription&lookup&drug=' + drugname, 'drugPopup', 'width=400,height=50,menubar=no,titlebar=no,left = 825,top = 400');
                                    drugPopup.opener = self;
                                    return true;
                            }


                    // check the form for required fields before submitting
                    var CheckForErrors = function(eObj) {
                    // REQUIRED FIELDS
                    if (CheckRequired('drug') == false) {
                    return false;
                    }
                    //if (CheckRequired('quantity') == false) { return false; }
                    //if (CheckRequired('unit') == false) { return false; }
                    //if (CheckRequired('size') == false) { return false; }
                    //if (CheckRequired('dosage') == false) { return false; }
                    //if (CheckRequired('form') == false) { return false; }
                    //if (CheckRequired('route') == false) { return false; }
                    //if (CheckRequired('interval') == false) { return false; }

                    return top.restoreSession();
                    };
                            function CheckRequired(objID) {

                            // for text boxes
                            if ($('#' + objID).is('input')) {
                            if ($('#' + objID).val() == "") {
                            alert("{/literal}{xl t='Missing a required field'}{literal}");
                                    $('#' + objID).css("backgroundColor", "pink");
                                    return false;
                            }
                            }

                            // for select boxes
                            if ($('#' + objID).is('select')) {
                            if ($('#' + objID).val() == "0") {
                            alert("{/literal}{xl t='Missing a required field'}{literal}");
                                    $('#' + objID).css("backgroundColor", "pink");
                                    return false;
                            }
                            }

                            return true;
                            }

        </script>
        {/literal}

</html>